<?php

namespace App\Http\Controllers\Source\Rong360;

use App\Constant\QueueKey;
use App\Events\AuthStepEvent;
use App\Facades\CommonPlatformRequestFacade;
use App\Http\Controllers\Source\BaseController;
use App\Jobs\NotifyBindCardStatus;
use App\Models\UserAuthStepEventLog;
use App\Models\UserBankCard;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Service\User;
use App\Models\UserBindCardException;
use Carbon\Carbon;
use App\Models\UserLoanRequest;

class BankCardController extends BaseController
{

    use User;

    /**
     * 申请绑卡，并判断是否需要发送验证码
     * @author cg
     * @date 2019-02-28 15:20
     * @param Request $request
     * @return mixed
     * @throws \Exception
     */
    public function applyBindCard(Request $request){
        $data = $this->initData($request);
        $order_no = $data['order_no'];
        $loan = UserLoanRequest::with('userGlobalStatus')->byTransId($order_no)->first();
        if(!$loan){
            return r360fail('借款信息不存在！');
        }
        $bank_card = $data['bank_card']; // 绑卡卡号
        $open_bank = $data['open_bank']; // 绑卡开户行
        $user_name = isset($data['user_name']) ? $data['user_name'] : $loan->userCert->name; // 姓名
        $id_number = isset($data['id_number']) ? $data['id_number'] : $loan->userCert->num; // 身份证号
        $user_mobile = isset($data['user_mobile']) ? $data['user_mobile'] : ''; // 手机号
        $bank_address = isset($data['bank_address']) ? $data['bank_address'] : ''; // 开户行地址
        $bankCardType = isset($data['bankCardType']) ? $data['bankCardType'] : ''; // 绑卡的卡类型  0：储蓄卡，1：信用卡
        $bind_card_src = $data['bind_card_src']; // 区分新旧卡 1=绑定新卡, 2=确认旧卡
        $extra_info = isset($data['extra_info']) ? $data['extra_info'] : ''; // 旧卡其他信息
        $bind_status = 1; // 发送验证码，bind_status=0          不发送验证码 bind_status=1
        // 是否需要发送验证码
        if($bind_card_src == 1){
            $bind_status = 0; // 发送
        }
        // 如果当前银行卡异常响应已经不下5次
        $countRequest = UserBindCardException::where(
            'user_id', $loan->user_id)
            ->where('card_num', $bank_card)
            ->where('cert_num', $id_number)
            ->where('phone_num', $user_mobile)
            ->where('real_name', $user_name)
            ->whereDate('created_at', Carbon::now()->format('Y-m-d'))->count();
        if ($countRequest >= 5) {
            return r360fail('您当前银行卡验证信息失败次数过多，请您核实银行卡信息后重试');
        }
        //获取绑定银行卡的短信验证码和请求编号
        if($bind_card_src == 1){
            $res = CommonPlatformRequestFacade::applyBindCard($bank_card, $id_number, $user_mobile, $user_name);
            if ($res['code'] === '01') {
                return r360Success('',[
                    'data' => ['bind_status' => $bind_status]
                ]);
            } else {
                //已绑定该银行卡,记录日常,后续和第三方沟通处理
                if ($res['code'] === '02') {
                    UserBindCardException::create([
                        'card_num' => $bank_card,
                        'cert_num' => $id_number,
                        'phone_num' => $user_mobile,
                        'real_name' => $user_name,
                        'code' => $res['code'],
                        'message' => $res['message'],
                        'order_num' => !empty($res['data']['orderNo']) ? $res['data']['orderNo'] : '',
                        'ip' => $request->getClientIp(),
                        'user_id' => $loan->user_id,
                    ]);
                }
                return r360fail('请求异常,' . $res['message']);
            }
        }else{
            // 选择旧卡
            \DB::beginTransaction();
            try{
                $userBackCard = UserBankCard::where('card_num', $bank_card)->first();
                $loan->cash_card_choice_id = $userBackCard->id;
                $loan->save();
                $log = [
                    'uid'=>$loan->user_id,
                    'step_id'=>$bank_card,
                    'type'=>UserAuthStepEventLog::STEP_BIND_CASH,
                    'loan_request_id'=>$loan->id,
                ];
                event(new AuthStepEvent($log));
                \DB::commit();
            }catch (\Exception $e){
                \DB::rollBack();
            }
            NotifyBindCardStatus::dispatch(['order_no'=>$order_no,'type'=>$bankCardType,'status'=>1,'msg'=>''])
                ->delay(now()->addSeconds(1))->onQueue(QueueKey::QUEUE_NOTIFY_BIND_CARD_STATUS);
            return r360Success('',[
                'data' => ''
            ]);
        }

    }

    /**
     * 绑卡确认
     * @param Request $request
     * @author cg
     * @date 2019-02-28 15:20
     * @return mixed
     * @throws \Exception
     */
    public function bindCard(Request $request){
        $data = $this->initData($request);
        $order_no = $data['order_no'];
        $loan = UserLoanRequest::with('userGlobalStatus')->byTransId($order_no)->first();
        if(!$loan){
            return r360fail('借款信息不存在！');
        }
        $bank_card = $data['bank_card']; // 绑卡卡号
        $open_bank = $data['open_bank']; // 绑卡开户行
        $user_name = $data['user_name']; // 姓名
        $id_number = $data['id_number']; // 身份证号
        $user_mobile = $data['user_mobile']; // 手机号
        $bank_address = $data['bank_address']; // 开户行地址
        $bankCardType = $data['bankCardType']; // 绑卡的卡类型  0：储蓄卡，1：信用卡
        $verify_code = $data['verify_code']; // 验证码

        // 验证银行卡是否可以签约
        $checkCardCanBind = UserBankCard::where('uid', $loan->user_id)->where('card_num', $bank_card)->first();
        //用户绑定过该银行，验证协议号是否有效
        if ($checkCardCanBind && $checkCardCanBind->hold_agreement_num) {
            $checkHoldAgreement = CommonPlatformRequestFacade::checkHoldAgreement($checkCardCanBind->hold_agreement_num);
            if ($checkHoldAgreement && $checkHoldAgreement['code'] === '01') {
                return r360fail('请求失败,' . $checkHoldAgreement['message']);
            } else {
                $checkCardCanBind->delete();
            }
        }
        // 获取银行卡相关信息，银行卡名称、银行卡全称、银行卡编码，是否是信用卡
        $codeRes = CommonPlatformRequestFacade::bankCode($bank_card);
        if ($codeRes['code'] !== '01') {
            return r360fail('请求失败,' . $codeRes['message']);
        }
        if ($bankCardType && $codeRes['data']['is_credit'] != $bankCardType) {
            return r360fail('请求失败, 该卡号不满足您的绑卡需求');
        }
        $status = 1;
        //记录用户银行卡信息
        \DB::beginTransaction();
        try{
            $bankCard = new UserBankCard();
            $bankCard->uid = $loan->user_id;
            $bankCard->card_username = $user_name;
            $bankCard->phone_num = $user_mobile;
            $bankCard->card_num = $bank_card;
            $bankCard->bank_address = $bank_address;
            //绑定银行卡操作
            $resBindCard = CommonPlatformRequestFacade::bindCardConfirm($bank_card, $loan, $verify_code, $order_no, $user_mobile, $user_name);
            if ($resBindCard['code'] !== '01') {
                $status = 0;
            }
            $bankCard->hold_agreement_num = !empty($resBindCard['data']['agreementNoEncase']) ? $resBindCard['data']['agreementNoEncase'] : '';
            $bankCard->order_num = !empty($resBindCard['data']['orderNo']) ? $resBindCard['data']['orderNo'] : '';
            $bankCard->bank_name = !empty($codeRes['data']['bank_name']) ? $codeRes['data']['bank_name'] : '';
            $bankCard->bank_name_show = !empty($codeRes['data']['bank_name_show']) ? $codeRes['data']['bank_name_show'] : '';
            $bankCard->bank_code = !empty($codeRes['data']['code']) ? $codeRes['data']['code'] : '';
            $bankCard->is_credit = UserBankCard::isCredit($codeRes['data']['is_credit']);
            $bankCard->save();
            $loan->cash_card_choice_id = $bankCard->id;
            $loan->save();
            $log = [
                'uid'=>$loan->user_id,
                'step_id'=>$bank_card,
                'type'=>UserAuthStepEventLog::STEP_BIND_CASH,
                'loan_request_id'=>$loan->id,
            ];
            event(new AuthStepEvent($log));
            \DB::commit();
        }catch (\Exception $e){
            \DB::rollBack();
            $status = 0;
        }
        NotifyBindCardStatus::dispatch(['order_no'=>$order_no,'type'=>$bankCardType,'status'=>$status,'msg'=>isset($resBindCard['message']) ?? ''])
            ->delay(now()->addSeconds(1))->onQueue(QueueKey::QUEUE_NOTIFY_BIND_CARD_STATUS);
        return r360Success('',[
            'data' => ['need_verify_code' => 0]
        ]);
    }


    /**
     * 银行卡列表
     * @author cg
     * @date 2019-02-28 15:20
     * @param Request $request
     * @return mixed
     * @throws \Exception
     */
    public function bankCardList(Request $request){
        $data = $this->initData($request);
        $order_id = isset($data['order_no']) ? $data['order_no'] : '';
        $loan = UserLoanRequest::with('userGlobalStatus')->byTransId($order_id)->first();
        if(!$loan){
            return r360fail('借款信息不存在！');
        }
        try{
            $data = $this->userBankList($loan->user_id);
            $returnData = [
                'order_no' => $order_id,
                'bank_card_list' => $data
            ];
            return r360Success('',[
                'data' => $returnData
            ]);
        }catch (\Exception $e){
            throw new \Exception($e->getMessage());
        }
    }
}
